<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// 处理预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// 只允许POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode([
        'status' => 'error',
        'message' => '只允许POST请求'
    ]);
    exit();
}

// 获取请求体
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// 验证请求数据
if (!$data || !isset($data['token']) || empty($data['token'])) {
    http_response_code(400);
    echo json_encode([
        'status' => 'error',
        'message' => '缺少token参数或token为空'
    ]);
    exit();
}

// 验证站点数据
if (!isset($data['siteName']) || !isset($data['siteDomain'])) {
    http_response_code(400);
    echo json_encode([
        'status' => 'error',
        'message' => '缺少站点信息'
    ]);
    exit();
}

$siteName = $data['siteName'];
$siteDomain = $data['siteDomain'];
$authType = 'localStorage';
if (isset($data['authType'])) {
    $authType = $data['authType'];
}
$authKey = '';
if (isset($data['authKey'])) {
    $authKey = $data['authKey'];
}
$token = $data['token'];

try {
    // 创建站点目录
    $siteId = 'site_' . str_replace('.', '_', $siteDomain);
    $siteDir = __DIR__ . '/sites/' . $siteId;
    if (!is_dir($siteDir)) {
        mkdir($siteDir, 0755, true);
    }
    
    // 保存token到站点专用文件
    $tokenFile = $siteDir . '/token.txt';
    if (file_put_contents($tokenFile, $token) === false) {
        throw new Exception('无法写入token文件');
    }
    
    // 保存站点信息
    $siteInfoFile = $siteDir . '/site_info.json';
    $siteInfo = [
        'site_name' => $siteName,
        'site_domain' => $siteDomain,
        'auth_type' => $authType,
        'auth_key' => $authKey,
        'last_updated' => date('Y-m-d H:i:s'),
        'token' => substr($token, 0, 10) . '...'
    ];
    
    if (file_put_contents($siteInfoFile, json_encode($siteInfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) === false) {
        throw new Exception('无法写入站点信息文件');
    }
    
    // 更新.env文件
    $envFile = __DIR__ . '/.env';
    updateEnvFile($envFile, 'SITE_' . strtoupper(str_replace('.', '_', $siteDomain)) . '_TOKEN', $token);
    updateEnvFile($envFile, 'SITE_' . strtoupper(str_replace('.', '_', $siteDomain)) . '_NAME', $siteName);
    updateEnvFile($envFile, 'SITE_' . strtoupper(str_replace('.', '_', $siteDomain)) . '_DOMAIN', $siteDomain);
    updateEnvFile($envFile, 'SITE_' . strtoupper(str_replace('.', '_', $siteDomain)) . '_AUTH_TYPE', $authType);
    updateEnvFile($envFile, 'SITE_' . strtoupper(str_replace('.', '_', $siteDomain)) . '_AUTH_KEY', $authKey);
    
    // 更新全局站点列表
    updateSitesList($siteId, $siteInfo);
    
    // 返回成功响应
    http_response_code(200);
    echo json_encode([
        'status' => 'success',
        'site_name' => $siteName,
        'token_received' => substr($token, 0, 10) . '...',
        'message' => 'Token已成功保存到站点: ' . $siteName
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'status' => 'error',
        'message' => '保存失败: ' . $e->getMessage()
    ]);
}

/**
 * 更新.env文件中的变量
 */
function updateEnvFile($envFile, $key, $value) {
    $lines = [];
    $keyFound = false;
    
    // 读取现有文件
    if (file_exists($envFile)) {
        $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    }
    
    // 查找并更新变量
    foreach ($lines as $i => $line) {
        if (strpos($line, $key . '=') === 0) {
            $lines[$i] = $key . '=' . $value;
            $keyFound = true;
            break;
        }
    }
    
    // 如果没找到，添加新行
    if (!$keyFound) {
        $lines[] = $key . '=' . $value;
    }
    
    // 写入文件
    if (file_put_contents($envFile, implode("\n", $lines) . "\n") === false) {
        throw new Exception('无法更新.env文件');
    }
}

/**
 * 更新站点列表
 */
function updateSitesList($siteId, $siteInfo) {
    $sitesListFile = __DIR__ . '/sites_list.json';
    $sitesList = [];
    
    if (file_exists($sitesListFile)) {
        $sitesList = json_decode(file_get_contents($sitesListFile), true) ?: [];
    }
    
    $sitesList[$siteId] = $siteInfo;
    
    if (file_put_contents($sitesListFile, json_encode($sitesList, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) === false) {
        throw new Exception('无法更新站点列表文件');
    }
}
?>